package org.meb.conquest.scan;

import java.io.StringWriter;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.meb.conquest.db.model.CardType;
import org.meb.conquest.db.util.Utils;
import org.meb.conquest.scan.model.Card;

public class WriteJsonCardHandler implements CardHandler {

//	private final String[] BASE_PROPS = { "type", "cost", "engageThreat", "startingThreat",
//			"threat", "willpower", "attack", "defense", "hitPoints", "illustrator", "number",
//			"questPoints", "quantity", "techName" };
//	private final String[] LANG_PROPS = { "name", "encounterSet", "encounterInfo", "sphere",
//			"shadowEffect", "trait", "text", "errata", "storyline" };
	
	private final String[] BASE_PROPS = { "number", "techName", "unique" };
	private final String[] LANG_PROPS = {  };

	private JsonNodeFactory jsonFactory;
	private ArrayNode cardsNode;
	private String langCode;
	private int count = 0;

	public WriteJsonCardHandler(String langCode) {
		this.langCode = langCode;
		jsonFactory = JsonNodeFactory.instance;
		cardsNode = jsonFactory.arrayNode();
	}

	@Override
	public void handle(Card card) {
//		card.setTechName(Utils.toTechName(card.getName()));
		card.setUnique(true);

		ObjectNode cardNode = cardsNode.addObject();
		for (String propertyName : BASE_PROPS) {
			try {
				Object propertyValue = PropertyUtils.getProperty(card, propertyName);
				if (propertyValue != null) {
					cardNode.put(propertyName, propertyValue.toString());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (StringUtils.isNotBlank(card.getSphere())) {
			cardNode.put("sphereCode", card.getSphere().toUpperCase());
		}
		cardNode.putObject("cardSetBase").put("techName", Utils.toTechName(card.getSetName()));

//		ObjectNode enNode = cardNode.putObject("langItems").putObject(langCode);
//		for (String propertyName : LANG_PROPS) {
//			try {
//				Object propertyValue = PropertyUtils.getProperty(card, propertyName);
//				if (propertyValue != null) {
//					enNode.put(propertyName, propertyValue.toString());
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		count++;
	}
	
	public int getCount() {
		return count;
	}

	@Override
	public String toString() {
		StringWriter writer = new StringWriter();
		try {
			new JsonFactory(new ObjectMapper()).createJsonGenerator(writer)
					.useDefaultPrettyPrinter().writeTree(cardsNode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writer.toString();
	}
}
